//
//  HZAreaPickerView.m
//  areapicker
//
//  Created by Cloud Dai on 12-9-9.
//  Copyright (c) 2012年 clouddai.com. All rights reserved.
//

#import "HZAreaPickerView.h"
#import <QuartzCore/QuartzCore.h>
#import "Helper.h"

#define kDuration 0.3

@interface HZAreaPickerView ()
{
    NSArray *provinces;
    HZAreaPickerInitOption _option;
}

@end

@implementation HZAreaPickerView

@synthesize delegate=_delegate;
@synthesize pickerStyle=_pickerStyle;
@synthesize locate=_locate;
@synthesize locatePicker = _locatePicker;
@synthesize sstates = _sstates;
@synthesize cities = _cities;
@synthesize areas = _areas;
@synthesize location = _location;

- (void)dealloc
{
    _areas = nil;
    _cities = nil;
    _sstates = nil;
    [_locate release];
    [_locatePicker release];
    [provinces release];
    [super dealloc];
}

-(HZLocation *)locate
{
    if (_locate == nil) {
        _locate = [[HZLocation alloc] init];
        _locate.state = @"";
        _locate.city = @"";
        _locate.district = @"";
    }
    
    return _locate;
}

- (id)initWithStyle:(HZAreaPickerStyle)pickerStyle delegate:(id<HZAreaPickerDelegate>)delegate withOption:(NSInteger)option
{

    self = [[[[NSBundle mainBundle] loadNibNamed:@"HZAreaPickerView" owner:self options:nil] objectAtIndex:0] retain];
    if (self) {
        self.delegate = delegate;
        self.pickerStyle = pickerStyle;
        self.locatePicker.dataSource = self;
        self.locatePicker.delegate = self;

        NSString *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES)[0];
        NSString *filename;
        
        if (option == HZAreaPickerInitNormalOption || option == HZAreaPickerInitAddtionnalOption) {
            filename = [path stringByAppendingPathComponent:@"location.plist"];
        }else{
            filename = [path stringByAppendingPathComponent:@"location_standard.plist"];
        }

        _sstates = [[NSArray arrayWithContentsOfFile:filename] retain];

        //临时补丁，转账中的修改银行信息
        if (_sstates != nil && _sstates.count > 0 && option == HZAreaPickerInitAddtionnalOption) {
            [_sstates removeObjectAtIndex:0];
        }
        
        if (_location == nil) {
            
            _cities = _sstates[0][@"cities"];
            
            self.locate.state = _sstates[0][@"name"];
            
            if (self.pickerStyle == HZAreaPickerWithStateAndCityAndDistrict) {
                
                
                if (_cities.count > 0) {
                    self.locate.city = _cities[0][@"name"];
                    
                    _areas = _cities[0][@"regions"];
                }
                else {
                    self.locate.city = @"";
                }
                
                if (_areas != nil && _areas.count > 0) {
                    self.locate.district = _areas[0][@"name"];
                }
                else {
                    self.locate.district = @"";
                }
            }
            
            else if (self.pickerStyle == HZAreaPickerWithStateAndCity){
                
                if (_cities.count > 0) {
                    self.locate.city = _cities[0][@"name"];
                    
                    _areas = _cities[0][@"regions"];
                }
                
                else {
                    self.locate.city = @"";
                }
                
                self.locate.district = @"";
            }

            else if (self.pickerStyle == HZAreaPickerWithState) {
                
                self.locate.city = @"";
                self.locate.district = @"";
            }
        }
//        //解析xml文件
//        NSString *filePath = nil;
//        
//        if (option == HZAreaPickerInitNormalOption) {
//            filePath = [[NSBundle mainBundle] pathForResource:@"LocList" ofType:@"xml"];
//        }else{
//            filePath = [[NSBundle mainBundle] pathForResource:@"LocList_standard" ofType:@"xml"];
//        }
//
//        NSData *xmlData = [[NSMutableData alloc] initWithContentsOfFile:filePath];
//        
//        NSXMLParser *xmlParser = [[NSXMLParser alloc] initWithData:xmlData];
//        
//        xmlParser.delegate = self;
//        
//        if ([xmlParser parse]) {
//            NSLog(@"The XML is parsed.");
//            
//        } else{
//            
//            [Helper showAllTextDialog:@"地址数据解析失败，请稍后再试" inView:self];
//        }
//        if (_location == nil) {
//            //加载数据
//            if (self.pickerStyle == HZAreaPickerWithStateAndCityAndDistrict) {
//                
//                //sstates为所有的一级城市的集合
//                //cities为所有二级城市的集合
//                //areas为所有三级城市的集合
//                
//                
//                _cities = [[_sstates objectAtIndex:0] objectForKey:@"City"];
//                
//                //保存当前选中的城市数据
//                self.locate.state = [[_sstates objectAtIndex:0] objectForKey:@"Name"];
//                if ([_cities count] > 0) {
//                    
//                    self.locate.city = [[_cities objectAtIndex:0] objectForKey:@"Name"];
//                    
//                    _areas = [[_cities objectAtIndex:0] objectForKey:@"Region"];
//                    
//                } else{
//                    self.locate.city = @"";
//                }
//                
//                if ([_areas count] > 0 && _areas != nil) {
//                    self.locate.district = [[_areas objectAtIndex:0] objectForKey:@"Name"];
//                    
//                } else{
//                    self.locate.district = @"";
//                }
//                
//                
//            } else if (self.pickerStyle == HZAreaPickerWithStateAndCity){
//                
//                _cities = [[_sstates objectAtIndex:0] objectForKey:@"City"];
//                
//                //保存当前选中的城市数据
//                self.locate.state = [[_sstates objectAtIndex:0] objectForKey:@"Name"];
//                
//                if ([_cities count] > 0) {
//                    self.locate.city = [[_cities objectAtIndex:0] objectForKey:@"Name"];
//                    
//                } else{
//                    self.locate.city = @"";
//                }
//                self.locate.district = @"";
//                
//            } else if (self.pickerStyle == HZAreaPickerWithState) {
//                
//                self.locate.state = [[_sstates objectAtIndex:0] objectForKey:@"Name"];
//                self.locate.city = @"";
//                self.locate.district = @"";
//            }
//        }
    }
    
    return self;
    
}

- (void)selectPickerView:(NSString *)location
{

    if (location != nil && ![@"" isEqualToString:location]) {
        
        NSInteger firstRow = 0;
        NSInteger secondRow = 0;
        NSInteger thirdRow = 0;
        
        NSArray *areaNameArray = [location componentsSeparatedByString:@" "];
        
        if (areaNameArray.count > 0) {
            
            for (int i = 0; i < areaNameArray.count; i++) {
                NSString *name = [areaNameArray objectAtIndex:i];

                //匹配一级城市
                if (i == 0) {
                    if (_sstates.count > 0) {
                        for (int j = 0; j < _sstates.count; j++) {
                            if ([[[_sstates objectAtIndex:j] objectForKey:@"name"] isEqualToString:name]) {
                                
                                firstRow = j;
                                //匹配成功保存
                                self.locate.state = name;
                                
                                //获得匹配成功的一级城市的二级城市集合
                                _cities = [[_sstates objectAtIndex:firstRow] objectForKey:@"cities"];
                                
                                break;
                                
                                //没有匹配到那么就默认第一个
                            }else{
                                self.locate.state = [[_sstates objectAtIndex:0] objectForKey:@"name"];
                                
                            }
                        }
                        
                        if (_cities.count > 0) {
                            self.locate.city = [[_cities objectAtIndex:0] objectForKey:@"name"];
                        }
                    }
                    
                    
                //匹配二级城市
                }else if (i == 1){
                    
                    if (_cities.count > 0) {
                        for (int j = 0; j < _cities.count; j++) {
                            if ([[[_cities objectAtIndex:j] objectForKey:@"name"] isEqualToString:name]) {
                                
                                secondRow = j;
                                
                                //匹配成功保存
                                self.locate.city = name;
                                //获得匹配成功的二级城市的三级城市集合
                                _areas = [[_cities objectAtIndex:secondRow] objectForKey:@"regions"];
                                break;
                                
                                //没有匹配到那么就默认第一个
                            }else{
                                
                                if (_cities.count > 0) {
                                    self.locate.city = [[_cities objectAtIndex:0] objectForKey:@"name"];
                                    
                                }
                                
                            }
                        }
                    }
                    
                //匹配三级城市
                }
                else if (i == 2){
                    if (_areas.count > 0) {
                        for (int j = 0; j < [_areas count]; j++) {
                            if ([[[_areas objectAtIndex:j] objectForKey:@"name"] isEqualToString:name]) {
                                
                                thirdRow = j;
                                //匹配成功保存
                                self.locate.district = name;
                                break;
                            }
                        }
                    }
                    
                }
            }
        }
        
        
        if (self.locate.state == nil) {
            self.locate.state = @"";
        }
        
        if (self.locate.city == nil) {
            self.locate.city = @"";
        }
        
        if (self.locate.district == nil) {
            self.locate.district = @"";
        }
        
        [_locatePicker selectRow:firstRow inComponent:0 animated:NO];
        
        if (self.pickerStyle == HZAreaPickerWithStateAndCityAndDistrict) {
            [_locatePicker selectRow:secondRow inComponent:1 animated:NO];
            [_locatePicker selectRow:thirdRow inComponent:2 animated:NO];
        } else if (self.pickerStyle == HZAreaPickerWithStateAndCity){
            [_locatePicker selectRow:secondRow inComponent:1 animated:NO];
        }
        
    }
}


#pragma mark - PickerView lifecycle

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    if (self.pickerStyle == HZAreaPickerWithStateAndCityAndDistrict) {
        return 3;
    } else if (self.pickerStyle == HZAreaPickerWithStateAndCity){
        return 2;
    } else{
        return 1;
    }
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    switch (component) {
            
        case 0:
            
            //如果数据源为空时，滑动pickerview会异常，必须设置一行。
            if ([_sstates count] == 0){
                
                return 1;
            }
            return [_sstates count];
            break;
        case 1:
            
            //如果数据源为空时，滑动pickerview会异常，必须设置一行。
            if ([_cities count] == 0){
                
                return 1;
            }
           
            return [_cities count];
            break;
        case 2:
            if (self.pickerStyle == HZAreaPickerWithStateAndCityAndDistrict) {
                
                //如果数据源为空时，滑动pickerview会异常，必须设置一行。
                if ([_areas count] == 0){
                    
                    return 1;
                }
                
                return [_areas count];
                break;
            }
        default:
            return 0;
            break;
    }
}

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    if (self.pickerStyle == HZAreaPickerWithStateAndCityAndDistrict) {
        
        switch (component) {
            case 0:
                
                return _sstates[row][@"name"];
                break;
            case 1:

                if ([_cities count] > 0) {
                    return [[_cities objectAtIndex:row] objectForKey:@"name"];
                }else{
                    return  @"";
                    
                }
                break;
            case 2:

                if ([_areas count] > 0) {
                    return [[_areas objectAtIndex:row] objectForKey:@"name"];
                }else{
                    return  @"";
                }
                break;
            default:
                return  @"";
                break;
        }
    } else if (self.pickerStyle == HZAreaPickerWithStateAndCity){
        switch (component) {
            case 0:
                return [[_sstates objectAtIndex:row] objectForKey:@"name"];
                break;
            case 1:
                if ([_cities count] > 0) {
                    return [[_cities objectAtIndex:row] objectForKey:@"name"];
                }else{
                    return  @"";
                }
                break;
                
            default:
                return @"";
                break;
        }
    }else{
        
        switch (component) {
            case 0:
                return [[_sstates objectAtIndex:row] objectForKey:@"name"];
                break;
                
            default:
                return @"";
                break;
        }
    }
}

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
    if (self.pickerStyle == HZAreaPickerWithStateAndCityAndDistrict) {
        
        switch (component) {
            case 0:
                
                //选择一个一级城市数据就刷新一次二级城市的数据
                _cities = [[_sstates objectAtIndex:row] objectForKey:@"cities"];

                [self.locatePicker selectRow:0 inComponent:1 animated:NO];
                [self.locatePicker reloadComponent:1];
                
                //保存一级城市的选择
                self.locate.state = [[_sstates objectAtIndex:row] objectForKey:@"name"];
                
                if ([_cities count] > 0) {
                    //选择一个一级城市数据就刷新一次三级城市的数据，并保存第一个二级城市
                    _areas = [[_cities objectAtIndex:0] objectForKey:@"regions"];
                    self.locate.city = [[_cities objectAtIndex:0] objectForKey:@"name"];
                    
                }else{
                    
                    //如果没有二级城市，那么就返回一个空的三级城市
                    _areas = [NSArray array];
                    self.locate.city = @"";
                }
                [self.locatePicker selectRow:0 inComponent:2 animated:NO];
                [self.locatePicker reloadComponent:2];
                                
                //保存第一个三级城市
                if ([_areas count] > 0) {
                    self.locate.district = [[_areas objectAtIndex:0] objectForKey:@"name"];
                } else{
                    self.locate.district = @"";
                }
                break;
            case 1:
                
                //选择一个二级城市数据就刷新一次三级城市的数据
                if ([_cities count] > 0) {
                    _areas = [[_cities objectAtIndex:row] objectForKey:@"regions"];
                    
                    //保存当前的选择
                    self.locate.city = [[_cities objectAtIndex:row] objectForKey:@"name"];
                    
                }else{
                    
                    //如果没有二级城市，那么就返回一个空的三级城市
                    _areas = [NSArray array];
                    
                    //保存当前的选择
                    self.locate.city = @"";
                }
                [self.locatePicker selectRow:0 inComponent:2 animated:NO];
                [self.locatePicker reloadComponent:2];
                
                if ([_areas count] > 0) {
                    self.locate.district = [[_areas objectAtIndex:0] objectForKey:@"name"];
                } else{
                    self.locate.district = @"";
                }

                break;
            case 2:
                
                //保存当前的选择
                if ([_areas count] > 0) {
                    self.locate.district = [[_areas objectAtIndex:row] objectForKey:@"name"];
                } else{
                    self.locate.district = @"";
                }
                break;
                
            default:
                break;
        }
        
        
    } else if (self.pickerStyle == HZAreaPickerWithStateAndCity){
        
        switch (component) {
            case 0:
                
                //选择一个一级城市数据就刷新一次二级城市的数据
                _cities = [[_sstates objectAtIndex:row] objectForKey:@"cities"];
                [self.locatePicker selectRow:0 inComponent:1 animated:NO];
                [self.locatePicker reloadComponent:1];
                
                //保存当前的选择
                self.locate.state = [[_sstates objectAtIndex:row] objectForKey:@"name"];
                
                if ([_cities count] > 0) {
                    self.locate.city = [[_cities objectAtIndex:0] objectForKey:@"name"];
                } else{
                    self.locate.city = @"";
                }
                
                break;
            case 1:
                
                //保存当前的选择
                if ([_cities count] > 0) {
                    self.locate.city = [[_cities objectAtIndex:row] objectForKey:@"name"];
                } else{
                    self.locate.city = @"";
                }
                
                break;
            default:
                
                break;
        }
        
        self.locate.district = @"";
        
    }else{
        
        self.locate.city = @"";
        self.locate.district = @"";
        switch (component) {
                
            case 0:
                               
                //保存当前的选择
                self.locate.state = [[_sstates objectAtIndex:row] objectForKey:@"name"];
                
                break;
            default:
                break;
        }
    }
    
    if([self.delegate respondsToSelector:@selector(pickerDidChangeStatus:)]) {
        [self.delegate pickerDidChangeStatus:self];
    }
}


#pragma mark - animation

- (void)showInView:(UIView *) view
{
    self.frame = CGRectMake(0, view.frame.size.height, self.frame.size.width, self.frame.size.height);
    [view addSubview:self];
    
    [UIView animateWithDuration:0.3 animations:^{
        self.frame = CGRectMake(0, view.frame.size.height - self.frame.size.height, self.frame.size.width, self.frame.size.height);
    }];
    
}

- (void)cancelPicker
{
    
    [UIView animateWithDuration:0.3
                     animations:^{
                         self.frame = CGRectMake(0, self.frame.origin.y+self.frame.size.height, self.frame.size.width, self.frame.size.height);
                     }
                     completion:^(BOOL finished){
                         [self removeFromSuperview];
                         
                     }];
    
}
#pragma mark - NSXMLParser Delegate
//
//- (void) parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName
//   namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
//     attributes:(NSDictionary *)attributeDict
//{
//    
//    
//    if ([elementName isEqualToString:@"Location"]) {
//        
//        //初始化states数组
//        if (_sstates == nil) {
//            _sstates = [[NSMutableArray alloc] init];
//        }
//    }
//    
//    //开始解析state标签
//    if ([elementName isEqualToString:@"State"]) {
//        
//        //初始化cities数组
//        if (_tmpCities == nil) {
//            _tmpCities = [[NSMutableArray alloc] init];
//        }
//        
//        //初始化一个state dictionary对象
//        if (_state == nil) {
//            _state = [[NSMutableDictionary alloc] init];
//        }
//        
//        
//        //开始解析state的属性，将属性值放入state dictionary对象中
//        
//        [_state setObject:[attributeDict objectForKey:@"Name"] forKey:@"Name"];
//        [_state setObject:[attributeDict objectForKey:@"Code"] forKey:@"Code"];
//        
//    }
//    
//    //开始解析cities标签
//    if ([elementName isEqualToString:@"City"]) {
//        //初始化region数组
//        if (_tmpRegions == nil) {
//            _tmpRegions = [[NSMutableArray alloc] init];
//        }
//        
//        //初始化一个state dictionary对象
//        if (_city == nil) {
//            _city = [[NSMutableDictionary alloc] init];
//        }
//        
//        //开始解析city的属性，将属性值放入city dictionary对象中
//        [_city setObject:[attributeDict objectForKey:@"Name"] forKey:@"Name"];
//        [_city setObject:[attributeDict objectForKey:@"Code"] forKey:@"Code"];
//        
//    }
//    
//    //开始解析region标签
//    if ([elementName isEqualToString:@"Region"]) {
//        
//        //初始化一个region dictionary对象
//        if (_region == nil) {
//            _region = [[NSMutableDictionary alloc] init];
//        }
//        
//        //开始解析region的属性，将属性值放入region dictionary对象中
//        [_region setObject:[attributeDict objectForKey:@"Name"] forKey:@"Name"];
//        [_region setObject:[attributeDict objectForKey:@"Code"] forKey:@"Code"];
//        
//    }
//}
//
//-(void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
//{
//    
//    if ([elementName isEqualToString:@"State"]) {
//        
//        //每解析完一个state标签，就将region数组添加到一个state dictionary对象中去
//        //并且将这个state dictionary对象添加到state数组里面去
//        
//        if (_tmpCities != nil) {
//            //此处array一定要重新开一块内存，否则在后面removeAllObjects时，会导致_state数组中的Region被removeAllObjects
//            NSArray *array = [NSArray arrayWithArray:_tmpCities];
//            
//            [_state setObject:array forKey:@"City"];
//            
//        }
//        
//        [_sstates addObject:_state];
//        
//        if (_tmpCities != nil && _tmpCities.count != 0) {
//            [_tmpCities removeAllObjects];
//        }
//        
//        _state = nil;
//        
//    }else if ([elementName isEqualToString:@"City"])
//    {
//        
//        //每解析完一个city标签，就将region数组添加到一个city dictionary对象中去
//        //并且将这个city dictionary对象添加到city数组里面去
//        
//        if (_tmpRegions != nil) {
//            
//            //此处array一定要重新开一块内存，否则在后面removeAllObjects时，会导致_city数组中的Region被removeAllObjects
//            NSArray *array = [NSArray arrayWithArray:_tmpRegions];
//            [_city setObject:array forKey:@"Region"];
//        }
//        [_tmpCities addObject:_city];
//        
//        
//        
//        if (_tmpRegions != nil && _tmpRegions.count != 0) {
//            [_tmpRegions removeAllObjects];
//        }
//        _city = nil;
//        
//    }else if ([elementName isEqualToString:@"Region"]){
//        
//        //每解析完一个region标签，就将一个region dictionary对象添加到region数组里面去
//        
//        [_tmpRegions addObject:_region];
//        
//        _region = nil;
//    }
//    
//}
@end
